package com.spzx.payment.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 付款信息表 服务实现类
 * </p>
 *
 * @author spzx
 * @since 2024-12-30
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    /**
     * 保存支付记录
     *
     * @param orderNo
     * @return
     */
/*    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //根据订单号查询付款信息
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));

        //幂等性判断
        if (paymentInfo != null) {
            //如果付款信息存在，则直接返回
            return paymentInfo;
        }
        //如果付款信息不存在，则创建一个新的付款信息对象
        paymentInfo = new PaymentInfo();
        //设置订单号
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setUserId(SecurityUtils.getUserId());
        paymentInfo.setPayType(2);


        //远程调用获取订单信息
        R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL == orderInfoResult.getCode()) {
            throw new ServiceException(orderInfoResult.getMsg());
        }

        OrderInfo orderInfo = orderInfoResult.getData();
        paymentInfo.setAmount(orderInfo.getTotalAmount());

        paymentInfo.setCallbackContent (
                orderInfo.getOrderItemList().size() > 1 ?
                        orderInfo.getOrderItemList() + "等商品" :
                        orderInfo.getOrderItemList().get(0).getSkuName());//设置回调内容
        paymentInfo.setPaymentStatus("0");//设置支付状态为未支付
        baseMapper.insert(paymentInfo);


        //其他字段可以根据实际业务需求进行填充
        return paymentInfo;
    }*/
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        // 根据订单号查询付款信息
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo)
        );

        // 幂等性判断：如果付款信息已存在，则直接返回
        if (paymentInfo != null) {
            return paymentInfo;
        }

        // 远程调用获取订单信息
        R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL == orderInfoResult.getCode()) {
            throw new ServiceException(orderInfoResult.getMsg());
        }

        // 获取订单信息
        OrderInfo orderInfo = orderInfoResult.getData();
        if (orderInfo == null) {
            throw new ServiceException("订单信息未找到");
        }

        // 创建新的付款信息对象
        paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setUserId(SecurityUtils.getUserId());
        paymentInfo.setPayType(2); // 设置支付类型，例如：2 表示支付宝

        // 设置支付金额
        paymentInfo.setAmount(orderInfo.getTotalAmount());

        // 设置回调内容
        List<OrderItem> orderItemList = orderInfo.getOrderItemList();
        String callbackContent = orderItemList.size() > 1// 如果订单包含多个商品，则将它们连接成一个字符串
                // 将每个  OrderItem 变换为其 SKU 名称// 使用空格连接所有 SKU 名称
                ? orderItemList.stream().map(OrderItem::getSkuName).collect(Collectors.joining(" "))
                : orderItemList.get(0).getSkuName();
        paymentInfo.setContent(callbackContent);// 返回商品交易内容

        // 设置支付状态为未支付
        paymentInfo.setPaymentStatus("0");

        // 插入到数据库
        baseMapper.insert(paymentInfo);

        return paymentInfo;
    }

    /**
     * 更新支付状态
     *
     * @param paramMap
     * @param payType
     */
    @Override
    public void updatePaymentStatus(PaymentInfo paymentInfo, Map<String, String> paramMap, int payType) {

        String tradeNo = paramMap.get("trade_no");// 支付宝交易号
        // 更新支付状态
        paymentInfo.setPayType(payType);// 设置支付类型
        paymentInfo.setPaymentStatus("1");// 设置支付状态为已支付
        paymentInfo.setTradeNo(tradeNo);// 设置支付宝交易号
        paymentInfo.setCallbackTime(new Date());// 设置回调时间
        paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));// 设置回调内容为参数的JSON字符串

        baseMapper.updateById(paymentInfo);
    }

}
